package com.ibeifeng.crm.find.realm;

import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.stereotype.Component;

import com.ibeifeng.crm.bean.User;
import com.ibeifeng.crm.service.UserFindService;


@Component
public class UserRealm extends AuthorizingRealm {
	@Resource
	UserFindService userFindService;
	@SuppressWarnings("unchecked")
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		System.out.println("*********用户角色与权限  doGetAuthorizationInfo*************");
		//取得用户名
		String username =(String) principals.getPrimaryPrincipal();
		//定义授权信息的返回数据
		SimpleAuthorizationInfo auth=new SimpleAuthorizationInfo();
		Map<String, Object> map=userFindService.listAuthByUserCode(username);
		Set<String> allRoles =(Set<String>) map.get("allRoles");
		Set<String> allPermission =(Set<String>) map.get("allPermission");
		auth.setRoles(allRoles);
		auth.setStringPermissions(allPermission);
		
		return auth;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken token) throws AuthenticationException {
		System.out.println("***********用户登录认证  doGetAuthenticationInfo**********");
		//登录认证的方法需要先执行，需要用它来判断登录的用户信息是否合法
		String username=(String) token.getPrincipal();
		User user=null;
		user=userFindService.get(username);
		
		
		if(user==null){
			throw new UnknownAccountException("该用户不存在!");
			
		}else{
			//进行密码验证
			String password=new String((char [])token.getCredentials());
			if(user.getUserPwd().equals(password)){
				AuthenticationInfo auth=new SimpleAuthenticationInfo(username, password,"userRealm");
				return auth;
			}else{
				throw new IncorrectCredentialsException("密码错误！");
			}
		}
		
	}

}
